package org.jeecg.modules.api.wlhy.driver;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ConvertUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.paycenter.channel.bankdocking.service.NhBankService;
import org.jeecg.modules.wlhy.bill.service.IHyDriverBillService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverAccountBook;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverAccountBookService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
* @Description: hy_driver_account_book
* @Author: jeecg-boot
* @Date:   2021-01-16
* @Version: V1.0
*/
@Api(tags="app司机端多级账簿")
@RestController
@RequestMapping("/api/wlhy/driver/accountbook")
@Slf4j
public class ApiDriverAccountBookController extends JeecgController<HyDriverAccountBook, IHyDriverAccountBookService> {
   @Autowired
   private IHyDriverAccountBookService hyDriverAccountBookService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired private IHySettingService settingService;
    @Autowired private NhBankService nhBankService;
    @Autowired private UserUtil userUtil;
    @Autowired private IHyDriverBillService hyDriverBillService;

    @ApiOperation(value="获取司机多级账簿信息", notes="获取司机多级账簿信息")
    @GetMapping(value = "/getAccountBookInfo")
    public Result<?> getAccountBookInfo() {
        HyDriver driver = userUtil.getDriver();
        HyDriverAccountBook accountBook = hyDriverAccountBookService.getOne(
                new QueryWrapper<HyDriverAccountBook>().eq("driver_id", driver.getId())
        );
        if(accountBook == null){
            return Result.error("未开通");
        }
        return Result.OK(accountBook);
    }

    @ApiOperation(value="获取司机多级账簿余额", notes="获取司机多级账簿余额")
    @GetMapping(value = "/getAccountBookBalance")
    public Result<?> getAccountBookBalance() {
        Map data =  hyDriverAccountBookService.getAccountBookInfo();
        return Result.OK(data);
    }

    @AutoLog(value = "开通多级账簿")
    @ApiOperation(value="开通多级账簿", notes="开通多级账簿")
    @PostMapping(value = "/addAccountBook")
    public Result<?> addAccountBook(@RequestBody HyDriverAccountBook hyDriverAccountBook) {
        HyConfig config = HyConfigUtils.getConfig();
        if(!config.getNhbankIzUse()){
            return Result.error("未开通服务！");
        }
        if(StringUtils.isEmpty(hyDriverAccountBook.getPayPwd())){
            return Result.error("支付密码不能为空！");
        }
        HyDriver driver = userUtil.getDriver();
        //是否开通过
        HyDriverAccountBook accountBook = hyDriverAccountBookService.getAccountBookByDriverId(driver.getId());
        if(accountBook != null){
            throw new JeecgBootException("不能重复开通");
        }
        hyDriverAccountBookService.addAccountBook(hyDriverAccountBook,driver);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "设置支付密码")
    @ApiOperation(value="设置支付密码", notes="设置支付密码")
    @PostMapping(value = "/setpwd")
    public Result<?> setpwd(@RequestBody JSONObject jsonObject) {
        String oldPwd = jsonObject.getString("oldpassword");
        String password = jsonObject.getString("password");
        if(StringUtils.isEmpty(oldPwd)){
            return Result.error("原始支付密码不能为空！");
        }
        if(StringUtils.isEmpty(password)){
            return Result.error("新支付密码不能为空！");
        }
        //验证支付密码
        hyDriverAccountBookService.editPayPwd(oldPwd,password);
        return Result.OK("修改成功！");
    }

    @AutoLog(value = "设置支付密码")
    @ApiOperation(value="设置支付密码", notes="设置支付密码")
    @PostMapping(value = "/resetpwd")
    public Result<?> resetpwd(@RequestBody JSONObject jsonObject) {
        String captcha = jsonObject.getString("captcha");
        String password = jsonObject.getString("password");
        if(StringUtils.isEmpty(captcha)){
            return Result.error("验证码！");
        }
        if(StringUtils.isEmpty(password)){
            return Result.error("新支付密码不能为空！");
        }
        LoginUser loginUser = UserUtil.getLoginUser();
        if(loginUser == null){
            return Result.error("未获取到登录信息");
        }
        String phone = loginUser.getPhone();
        Object code = redisUtil.get(phone);
        if (!captcha.equals(code)) {
            return Result.error("验证码错误");
        }
        //验证支付密码
        hyDriverAccountBookService.ResetPayPwd(password);
        return Result.OK("修改成功！");
    }

    @AutoLog(value = "司机提现")
    @ApiOperation(value="司机提现", notes="司机提现")
    @PostMapping(value = "/tx")
    public Result<?> tx(@RequestBody JSONObject jsonObject) {

        String settingValue = settingService.getSettingValueByTag2("bank_relative");
        if (!"1".equals(settingValue)) {
            return Result.error("系统暂时关闭支付功能！");
        }
        HyConfig config = HyConfigUtils.getConfig();
        if (!config.getNhbankIzUse()) {
            return Result.error("未开通服务！");
        }

        String driverBankId = jsonObject.getString("driverBankId");
        String password = jsonObject.getString("password");
        String amt = jsonObject.getString("amt");
        if (StringUtils.isEmpty(password)) {
            return Result.error("支付密码不能为空！");
        }
        if (!ConvertUtil.isMoney(amt)) {
            return Result.error("提现金额不正确！");
        }

        if (StringUtils.isEmpty(driverBankId)) {
            return Result.error("银行卡不能为空！");
        }
        HyDriver driver = userUtil.getDriver();

        HyDriverAccountBook accountBook = hyDriverAccountBookService.getOne(
                new QueryWrapper<HyDriverAccountBook>().eq("driver_id", driver.getId())
        );
        if (accountBook == null) {
            return Result.error("未获取到钱包信息！");
        }
        String encryptPayPwd = PasswordUtil.encrypt(accountBook.getLogAccNo(), password,  PasswordUtil.BSalt);
        if(!StringUtils.equals(encryptPayPwd,accountBook.getPayPwd())){
            return Result.error("支付密码错误！");
        }

        //判断次数限制
        if (HyCfgUtil.isUsed2("driver_withdrawal_restrictions")) {
            String driver_withdrawal_restrictions = HyCfgUtil.getCfgValue2("driver_withdrawal_restrictions");
            if (StringUtils.isNotEmpty(driver_withdrawal_restrictions)) {
                int txnums = Integer.parseInt(driver_withdrawal_restrictions);
                int txCounts = hyDriverBillService.getDriverTxCountsByDate(driver.getId(), new Date());
                if (txCounts >= txnums) {
                    return Result.error(String.format("日提现次数限额%s次，已提现%s次，超过提现次数,请次日提现！", txnums, txCounts));
                }
            }
        }
        BigDecimal bdAmt = new BigDecimal(amt);
        return nhBankService.tx(accountBook , driver, driverBankId, bdAmt);
    }


}
